package com.demo.lease;

import com.demo.common.constant.WebConstants;
import com.demo.common.model.House;
import com.demo.common.model.Lease;
import com.demo.common.model.User;
import com.demo.common.util.WebUtil;
import com.demo.house.HouseService;
import com.demo.user.UserChangePwdValidator;
import com.demo.user.UserInterceptor;
import com.demo.user.UserService;
import com.demo.user.UserValidator;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;


@Before(LeaseInterceptor.class)
public class LeaseController extends Controller {


    @Inject
    LeaseService leaseService;

    @Inject
    HouseService houseService;

    public void index() {
        Kv cond=Kv.create();
        if(StrKit.notBlank(getPara("housename"))){
            cond.set("housename",getPara("housename"));
        }
        if(StrKit.notBlank(getPara("houselocation"))){
            cond.set("houselocation",getPara("houselocation"));
        }
        User user=getSessionAttr("user");
        if(user.getRole().equals(WebConstants.HOUSE)){ //房东
            cond.set("userid",user.getId());
        }else if(user.getRole().equals(WebConstants.LEASEER)){ //租户
            cond.set("leaseid",user.getId());
        }
        setAttr("leasePage", leaseService.paginate(getParaToInt(0, 1), 10,Kv.by("cond",cond)));
        render("lease.html");
    }

    public void add() {
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
     * 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    @Before(LeaseValidator.class)
    public void save() {
        getBean(Lease.class);
        redirect("/lease");
    }

    public void edit() {
        setAttr("lease", leaseService.findById(getParaToInt()));
    }

    /**
     * save 与 update 的业务逻辑在实际应用中也应该放在 serivce 之中，
     * 并要对数据进正确性进行验证，在此仅为了偷懒
     */
    @Before(LeaseValidator.class)
    public void update() {
        getBean(Lease.class).update();
        redirect("/lease");
    }

    public void delete() {
        Lease lease=leaseService.findById(getParaToInt());
        House house=houseService.findById(lease.getHouseid());
        house.setStatus(WebConstants.NOLEASEER);
        house.update();
        leaseService.deleteById(getParaToInt());
        redirect("/lease");
    }

    //租赁成交
    public void deal(){
        Lease lease=leaseService.findById(getParaToInt());
        lease.setStatus(WebConstants.YESLEASEER);
        lease.update();
        House house=houseService.findById(lease.getHouseid());
        house.setStatus(WebConstants.YESLEASEER);
        house.update();
        redirect("/lease");
    }
}
